const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async listAction() {
    const model = this.model('industry');
    const data = await model.order(['sort ASC']).select();
    const newData = data.filter(item=>{
      item.children = []
      return item.parentId === 0
    })
    for (const item of data) {
      if(item.parentId === 0){
        
      }else{
        for (const newItem of newData) {
          if(item.parentId === newItem.id){
            newItem.children.push(item)
          }
        }
      }
    }
    return this.success(newData);
  }


  async singleAction(){
    const id = this.get('id');
    const data = await this.model('industry').where({id:id}).find();
    return this.success(data);
  }

  async dictAction(){
    const parent = this.get('parent');
    let data;
    if(parent) {
      data = await this.model('industry').where({parentId:parent}).select();
    }else{
      data = await this.model('industry').where({parentId:0}).select();
    }
    return this.success(data);
  }

  async putAction() {

    const values = this.post();
    const id = this.post('id');
    const model = this.model('industry');

    values.label = values.name

    if (id > 0) {
      await model.where({id: id}).update(values);
    } else {
      delete values.id;
      await model.add(values);
    }
    return this.success(values);
  }

  async deleteAction() {
    const id = this.get('id');
    await this.model('industry').where({id: id}).limit(1).delete();

    return this.success();
  }
};
